package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.product.ProductOrderWarmHeart;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.base.ISmsTemplateService;
import com.pig4cloud.pig.module.service.product.IProductOrderWarmHeartService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.springboot.sms.core.SmsTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 购物需要购买的暖心保订单Controller
 *
 * @author ruoyi
 * @date 2022-11-14
 */
@Validated
@Api(value = "购物需要购买的暖心保订单控制器", tags = {"购物需要购买的暖心保订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/product/order/warm/heart")
public class ProductOrderWarmHeartController {

    private final IProductOrderWarmHeartService productOrderWarmHeartService;
	private final IWxTemplateService wxTemplateService;
	private final IWxUserService wxUserService;
	private final ISmsTemplateService smsTemplateService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询购物需要购买的暖心保订单列表
     */
    @ApiOperation("查询购物需要购买的暖心保订单列表")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:list')")
    @GetMapping("/list")
    public TableDataInfo<ProductOrderWarmHeart> list(@Validated ProductOrderWarmHeart productOrderWarmHeart) {
        QueryWrapper<ProductOrderWarmHeart> qw = new QueryWrapper<>();
        if(productOrderWarmHeart.getState() != null){
        	qw.eq("state",productOrderWarmHeart.getState());
		}
        if(StrUtil.isNotEmpty(productOrderWarmHeart.getRealName())){
        	qw.like("real_name",productOrderWarmHeart.getRealName())
				.or().like("phone_num",productOrderWarmHeart.getRealName())
				.or().like("id_no",productOrderWarmHeart.getRealName());
		}
		qw.orderByDesc("id");
        TableDataInfo<ProductOrderWarmHeart> td = PageUtils.buildDataInfo(productOrderWarmHeartService.page(PageUtils.buildPage(),qw));
        List<ProductOrderWarmHeart> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (ProductOrderWarmHeart heart : list){
        		if(StrUtil.isNotEmpty(heart.getPayImgUrl())){
					heart.setPayImgUrl(imgUrl + heart.getPayImgUrl());
				}
        		WxUser wxUser = wxUserService.findById(heart.getUserId());
        		if(wxUser!=null){
					heart.setUserNo(wxUser.getUserNo());
				}
			}
		}
        return td;
    }

    /**
     * 导出购物需要购买的暖心保订单列表
     */
    @ApiOperation("导出购物需要购买的暖心保订单列表")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:export')")
    @SysLog("购物需要购买的暖心保订单")
    @GetMapping("/export")
    public List export(@Validated ProductOrderWarmHeart productOrderWarmHeart) {
		QueryWrapper<ProductOrderWarmHeart> qw = new QueryWrapper<>();
		if(productOrderWarmHeart.getState() != null){
			qw.eq("state",productOrderWarmHeart.getState());
		}
		if(StrUtil.isNotEmpty(productOrderWarmHeart.getRealName())){
			qw.like("real_name",productOrderWarmHeart.getRealName())
				.or().like("phone_num",productOrderWarmHeart.getRealName())
				.or().like("id_no",productOrderWarmHeart.getRealName());
		}
        List<ProductOrderWarmHeart> list = productOrderWarmHeartService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (ProductOrderWarmHeart heart: list){
				if(heart.getState() == 0){
					heart.setStateTxt("未投保");
				} else if(heart.getState() == 1){
					heart.setStateTxt("已投保");
				}
			}
		}
        // ExcelUtil<ProductOrderWarmHeart> util = new // ExcelUtil<ProductOrderWarmHeart>(ProductOrderWarmHeart.class);
        return  list;// util.exportExcel(list, "购物需要购买的暖心保订单");
    }

    /**
     * 获取购物需要购买的暖心保订单详细信息
     */
    @ApiOperation("获取购物需要购买的暖心保订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:query')")
    @GetMapping("/{id}")
    public R<ProductOrderWarmHeart> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrderWarmHeart productOrderWarmHeart = productOrderWarmHeartService.getById(id);
        return R.ok(productOrderWarmHeart);
    }


	/**
	 * 获取购物需要购买的暖心保订单详细信息
	 */
	@ApiOperation("获取购物需要购买的暖心保订单详细信息")
	@PreAuthorize("@pms.hasPermission('module:orderWarm:query')")
	@GetMapping("/getByOrderId/{orderId}")
	public R<ProductOrderWarmHeart> getByOrderId(@NotNull(message = "主键不能为空") @PathVariable("orderId") Long orderId) {
		QueryWrapper<ProductOrderWarmHeart> qw = new QueryWrapper<>();
		qw.eq("order_id", orderId);
		qw.last("limit 1");
		ProductOrderWarmHeart productOrderWarmHeart = productOrderWarmHeartService.getOne(qw);
		return R.ok(productOrderWarmHeart);
	}

    /**
     * 新增购物需要购买的暖心保订单
     */
    @ApiOperation("新增购物需要购买的暖心保订单")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:add')")
    @SysLog("购物需要购买的暖心保订单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ProductOrderWarmHeart productOrderWarmHeart) {
        return R.okByRow(productOrderWarmHeartService.save(productOrderWarmHeart) ? 1 : 0);
    }

    /**
     * 修改购物需要购买的暖心保订单
     */
    @ApiOperation("修改购物需要购买的暖心保订单")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:edit')")
    @SysLog("购物需要购买的暖心保订单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ProductOrderWarmHeart productOrderWarmHeart) {

		if(productOrderWarmHeart.getState() == 1){
			productOrderWarmHeart.setBuyWarmHeartTime(new Date());
		}
    	boolean bl = productOrderWarmHeartService.updateById(productOrderWarmHeart);
    	if(bl){
    		if(productOrderWarmHeart.getState() == 1){
				WxUser user = wxUserService.findById(productOrderWarmHeart.getUserId());
				if(user != null){
					SmsTemplate template = smsTemplateService.selectByUniqueColumn("sms_type",5);
					//短信提示
//					SendSms sendSms = new SendSms();
//					//请求失败这里会抛ClientException异常
//					JSONObject smsJson = new JSONObject();
//					try {
//						sendSms.send(productOrderWarmHeart.getPhoneNum(),smsJson,template);
//					} catch (ClientException e) {
//						e.printStackTrace();
//					}
					// 公众号推送
					wxTemplateService.sendWxMsgByWarmHeart(user,productOrderWarmHeart);
				}
			}
		}
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除购物需要购买的暖心保订单
     */
    @ApiOperation("删除购物需要购买的暖心保订单")
    @PreAuthorize("@pms.hasPermission('module:orderWarm:remove')")
    @SysLog("购物需要购买的暖心保订单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(productOrderWarmHeartService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
